import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 任务列表
    list: [],
    // 下个任务的id
    nextId: 5,
    // 输入框内容
    inputVal: '',
    // 当前显示列表
    showList: 'All'
  },
  mutations: {
    toList (state, list) {
      state.list = list
    },
    // 内容同步
    infoChange (state, info) {
      state.inputVal = info
    },
    // 添加任务
    addItem (state) {
      const newItem = {
        id: state.id,
        info: state.inputVal,
        done: false
      }
      state.list.push(newItem)
    },
    // 删除任务
    removeItem (state, id) {
      const i = state.list.findIndex(x =>
        x.id === id
      )
      if (id !== -1) {
        state.list.splice(i, 1)
      }
    },
    // 改变状态
    changeStatus (state, params) {
      const i = state.list.findIndex(x =>
        x.id === params.id
      )
      state.list[i].done = params.status
    },
    // 清除已完成
    clearDone (state) {
      state.list = state.list.filter(x => x.done === false)
    },
    // 改变显示列表
    showLis (state, nowList) {
      state.showList = nowList
    }
  },
  actions: {
    // 初始化任务列表
    getlist (context) {
      axios.get('/list.json').then(({ data }) => {
        context.commit('toList', data)
      })
    }
  },
  getters: {
    // 返回未完成任务列表
    noDoneList (state) {
      const list = state.list.filter(x => x.done === false)
      return list
    },
    // 给显示列表提供数据源
    showLis (state) {
      // 判断当前显示按钮状态，返回相应的列表
      if (state.showList === 'All') {
        return state.list
      } else if (state.showList === 'Undone') {
        const list = state.list.filter(x => x.done === false)
        return list
      } else {
        const list = state.list.filter(x => x.done === true)
        return list
      }
    }
  },
  modules: {}
})
